package cn.wk.util;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class JsonRes {
    public static JSONObject res(int code, Object data, String msg) {
        JSONObject json = new JSONObject();
        json.put("code", code);
        json.put("data", data);
        json.put("msg", msg);
        return json;
    }
    public static JSONObject res(int code, int count,Object data) {
        JSONObject json = new JSONObject();
        json.put("code", code);
        json.put("count",count);
        json.put("data", data);
        return json;
    }

    public static JSONObject res(int code, String msg) {
        return res(code, null, msg);
    }

    public static JSONObject res(int code, Object data) {
        return res(code, data, "success");
    }

    public static JSONObject res() {
        return res(0, "success");
    }

    public static JSONObject res(Object data) {
        return res(0, data, "success");
    }

    public static JSONObject error(String msg) {
        return res(-1, msg);
    }

    public static JSONObject error() {
        return error("Bad Request");
    }
    //对数组进行排序
    public static JSONArray jsonArraySort(JSONArray result, String sortColName, boolean isAsc) {
        JSONArray sortedJsonArray = new JSONArray();
        List<JSONObject> jsonValues = new ArrayList<JSONObject>();
        for (int i = 0; i < result.size(); i++) {
            jsonValues.add(result.getJSONObject(i));
        }

        // 将 JSONArray 转换成 List,本质上还是对 List 进行排序
        Collections.sort(jsonValues, new Comparator<JSONObject>() {
            @Override
            public int compare(JSONObject o1, JSONObject o2) {
                String valA = o1.getString(sortColName);
                String valB = o2.getString(sortColName);
                if (isAsc) {
                    // 升序
                    return -valB.compareTo(valA);
                } else {
                    return -valA.compareTo(valB);
                }
            }
        });
        for (int i = 0; i < result.size(); i++) {
            sortedJsonArray.add(jsonValues.get(i));
        }
        return sortedJsonArray;
    }
}
